package com.hmall.controller.back;


//后台资质审核

import com.hdmall.business.common.common.ServerResponse;

import com.hmall.mapper.*;

import com.hmall.model.*;

import com.hmall.service.PlanManageService;
import com.hmall.service.UserService;


import com.hmall.vo.*;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;


import java.util.Calendar;
import java.util.Date;
import java.util.List;


@RestController
@RequestMapping("/manage/exam")
@Api(value = "资质认证管理操作API", description = "资质认证管理类API说明")
public class AptExamManagerController {
    private final
    UserService iUserService;
    private final
    SysUserMapper sysUserMapper;
    private final
    SysUserTempMapper sysUserTempMapper;
    private final
    SysDeptMapper sysDeptMapper;
    private final
    SysUserDeptMapper sysUserDeptMapper;
    private final
    SysUserDetailMapper sysUserDetailMapper;
    private final
    SysRoleMapper sysRoleMapper;
    private final
    MallShopMapper mallShopMapper;
    private final
    SysRoleDeptMapper sysRoleDeptMapper;
    private final
    SysCustomerMapper sysCustomerMapper;
    private final
    SysDeptCustomerMapper sysDeptCustomerMapper;
    private final
    PlanManageService planManageService;
    private final
    MallProductPlanMapper mallProductPlanMapper;

    @Autowired
    public AptExamManagerController(SysUserMapper sysUserMapper, UserService iUserService, SysUserTempMapper sysUserTempMapper, SysDeptMapper sysDeptMapper, SysUserDeptMapper sysUserDeptMapper, SysUserDetailMapper sysUserDetailMapper, SysRoleMapper sysRoleMapper, PlanManageService planManageService, SysCustomerMapper sysCustomerMapper, MallShopMapper mallShopMapper, SysDeptCustomerMapper sysDeptCustomerMapper, SysRoleDeptMapper sysRoleDeptMapper, MallProductPlanMapper mallProductPlanMapper) {
        this.sysUserMapper = sysUserMapper;
        this.iUserService = iUserService;
        this.sysUserTempMapper = sysUserTempMapper;
        this.sysDeptMapper = sysDeptMapper;
        this.sysUserDeptMapper = sysUserDeptMapper;
        this.sysUserDetailMapper = sysUserDetailMapper;
        this.sysRoleMapper = sysRoleMapper;
        this.planManageService = planManageService;
        this.sysCustomerMapper = sysCustomerMapper;
        this.mallShopMapper = mallShopMapper;
        this.sysDeptCustomerMapper = sysDeptCustomerMapper;
        this.sysRoleDeptMapper = sysRoleDeptMapper;
        this.mallProductPlanMapper = mallProductPlanMapper;
    }

    /*  @GetMapping("listExam")
      @ApiOperation("列出所有的资质认证")
      public ServerResponse<PageVo> listExam(@RequestParam(defaultValue = "pageNum", value = "1") int pageNum,
                                             @RequestParam(defaultValue = "pageSize", value = "10") int pageSize){

          return iUserService.listExam(pageNum, pageSize);
      }*/
    @GetMapping("filterExam")
    @ApiOperation("筛选资质")
    public ServerResponse<PageVo> filterExam() {
        return null;
    }

    //face /back
    @PostMapping("idImgCastWord")
    @ApiOperation("身份证图片转换成文字")
    public ServerResponse<ImgLegalId> idImgCastWord(@RequestBody ExamVo examVo) {
        return iUserService.idImgCastWord(examVo.getUrl(), "face");
    }

    @PostMapping("licImgCastWord")
    @ApiOperation("营业执照图片转换成文字")
    public ServerResponse licImgCastWord(@RequestBody ExamVo examVo) {
        return iUserService.licImgCastWord(examVo.getUrl());
    }

    @GetMapping("GetExamList")
    @ApiOperation(value = "获取审核信息列表")
    public ServerResponse GetExamList(
            @RequestParam(value = "pageNum", defaultValue = "1")
                    int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "100")
                    int pageSize) {
        return iUserService.getAptExamList(pageNum, pageSize);
    }

    @GetMapping("GetUnExamList")
    @ApiOperation(value = "获取未审核信息列表")
    public ServerResponse GetUnExamList(
            @RequestParam(value = "pageNum", defaultValue = "1")
                    int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "100")
                    int pageSize) {
        return iUserService.getUnExamList(pageNum, pageSize);
    }

    @GetMapping("GetUnpassExamList")
    @ApiOperation(value = "获取未通过审核信息列表")
    public ServerResponse GetUnpassExamList(
            @RequestParam(value = "pageNum", defaultValue = "1")
                    int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "100")
                    int pageSize) {
        return iUserService.getUnpassExamList(pageNum, pageSize);
    }

    @GetMapping("GetPassExamList")
    @ApiOperation(value = "获取通过审核信息列表")
    public ServerResponse GetPassExamList(
            @RequestParam(value = "pageNum", defaultValue = "1")
                    int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "100")
                    int pageSize) {
        return iUserService.getPassExamList(pageNum, pageSize);
    }

    @DeleteMapping("DeleteExam")
    @ApiOperation(value = "删除资质审核")
    public ServerResponse DeleteExam(Integer id) {
        Integer user_id = sysUserTempMapper.selectByPrimaryKey(id).getUserId();
        sysUserDetailMapper.deleteByUserId(user_id);
        sysUserDeptMapper.deleteByUserId(user_id);

        int count = sysUserTempMapper.deleteByPrimaryKey(id);

        if (count == 0) {
            return ServerResponse.createByErrorMessage("删除失败");
        } else {
            return ServerResponse.createBySuccess("删除成功");
        }
    }

    @GetMapping("GetExams")
    @ApiOperation(value = "获取资质审核信息")
    public ServerResponse GetExams(Integer id) {
        SysUserTemp sysUserTemp = sysUserTempMapper.selectByPrimaryKey(id);
        String username = sysUserMapper.selectByUserId(sysUserTemp.getUserId())
                .getUsername();
        SysTempVo sysTempVo = new SysTempVo();
        sysTempVo.setSysUserTemp(sysUserTemp);
        sysTempVo.setUsername(username);

        return ServerResponse.createBySuccess(sysTempVo);
    }

    @PostMapping("passExam")
    @ApiOperation(value = "通过审核")
    public ServerResponse passExam(@RequestBody
                                           ExamDetailVo examDetailVo) {
        SysUserTemp sysUserTemp = sysUserTempMapper.selectByPrimaryKey(examDetailVo.getTemp_id());
        System.out.println(examDetailVo.toString());

        SysDept dept = new SysDept();
        Boolean flag = false;
        dept.setName(examDetailVo.getBus_name());
        dept.setDelFlag("0");
        System.out.println(examDetailVo.getType());
        System.out.println(examDetailVo.getType() == 0);

        if (examDetailVo.getType() == 0) {
            dept.setParentId(18);
            flag = true;
        } else {
            dept.setParentId(17);
        }

        Date now = new Date();
        dept.setCreateTime(now);

        Integer dept_id = sysDeptMapper.selectIdByName2(examDetailVo.getBus_name());
        Integer customer_id = sysCustomerMapper.selectCustomerByName(examDetailVo.getBus_name());
        Integer user_id = sysUserTempMapper.selectByPrimaryKey(examDetailVo.getTemp_id())
                .getUserId();
        SysUser sysUser2 = sysUserMapper.selectByPrimaryKey(user_id);
        Integer num = sysUserDeptMapper.checkBinding(sysUser2.getUsername(), dept_id);
        if (num != 0) {
            return ServerResponse.createByErrorMessage("该手机号已经绑定该公司");
        }
        if ((dept_id == null) || (dept_id == ' ')) {
            sysDeptMapper.insert(dept);

            SysCustomer sysUserDetail = new SysCustomer();
            sysUserDetail.setLinkmanName(examDetailVo.getName());
            sysUserDetail.setLinkmanTel(examDetailVo.getLinkman_tel());
            sysUserDetail.setBusName(examDetailVo.getBus_name());
            sysUserDetail.setBusPersonName(examDetailVo.getBus_person_name());
            sysUserDetail.setBusPersonId(examDetailVo.getBus_person_id());
            sysUserDetail.setBusAddress(examDetailVo.getBus_address());
            sysUserDetail.setCaptial(examDetailVo.getCaptial());
            sysUserDetail.setValidPeriod(examDetailVo.getEstablishDate() + "到" +
                    examDetailVo.getValidPeriod());
            sysUserDetail.setBusiness(examDetailVo.getBusiness());
            sysUserDetail.setRegNum(examDetailVo.getReg_num());
            sysUserDetail.setInvoiceTitle(examDetailVo.getInvoice_title());
            sysUserDetail.setInvoiceTitleAddr(examDetailVo.getInvoice_title_addr());
            sysUserDetail.setTaxNum(examDetailVo.getTax_num());
            sysUserDetail.setBankName(examDetailVo.getBank_name());
            sysUserDetail.setBankNumber(examDetailVo.getBank_number());
            sysUserDetail.setDealerId(examDetailVo.getDealer_id());
            sysUserDetail.setCreateTime(new Date());
            sysUserDetail.setTaxCertUrl(sysUserTemp.getTaxCertUrl());
            sysUserDetail.setIdFaceUrl(sysUserTemp.getIdFaceUrl());
            sysUserDetail.setIdBackUrl(sysUserTemp.getIdBackUrl());
            sysUserDetail.setLicenseUrl(sysUserTemp.getLicenseUrl());
            sysUserDetail.setAuthUrl(sysUserTemp.getAuthUrl());
            sysCustomerMapper.insert(sysUserDetail);

            customer_id = sysCustomerMapper.selectCustomerByName(sysUserDetail.getBusName());
            dept_id = sysDeptMapper.selectIdByName2(examDetailVo.getBus_name());

            SysDeptCustomer sysDeptCustomer = new SysDeptCustomer();
            sysDeptCustomer.setDeptId(dept_id);
            sysDeptCustomer.setCustomerId(customer_id);
            sysDeptCustomerMapper.insert(sysDeptCustomer);
        }
        sysUserTempMapper.passExam(examDetailVo.getTemp_id(),
                examDetailVo.getOpinion());

        if (flag) {
            SysRole sysRole = new SysRole();
            sysRole.setRoleName(examDetailVo.getBus_name() + "管理员");

            Date date = new Date();
            sysRole.setCreateTime(date);
            sysRole.setRoleCode(examDetailVo.getBus_name() + "ROLE_ADMIN");
            sysRole.setDelFlag("0");
            sysRole.setRoleDesc(examDetailVo.getBus_name() + "管理员");
            sysRoleMapper.insert(sysRole);

            Integer role_id = sysRoleMapper.selectIdByName(examDetailVo.getBus_name() +
                    "管理员");
            SysRoleDept sysRoleDept = new SysRoleDept();
            sysRoleDept.setDeptId(dept_id);
            sysRoleDept.setRoleId(role_id);
            sysRoleDeptMapper.insert(sysRoleDept);

            MallShop mallShop = new MallShop();
            mallShop.setDeptId(dept_id);
            mallShop.setShopName(examDetailVo.getBus_name());
            mallShop.setShopCreateDate(date);
            mallShopMapper.insert(mallShop);
        } else {
//            SysUserTemp sysUserTemp = new SysUserTemp();
//            sysUserTemp.setUserId(user_id);
//            sysUserTemp.setStatus(3);
//            sysUserTemp.setLinkmanName(examDetailVo.getLinkman_name());
//            sysUserTemp.setCreateTime(new Date());
//            sysUserTemp.setOpinion(examDetailVo.getOpinion());
//            sysUserTemp.setType(9);
//            sysUserTempMapper.insert(sysUserTemp);
            SysUserDept sysUserDept = sysUserDeptMapper.selectByUserId(user_id);
            if (sysUserDept == null) {
                SysUserDept sysUserDept2 = new SysUserDept();
                sysUserDept2.setDeptId(dept_id);
                sysUserDept2.setUserId(user_id);
                sysUserDeptMapper.insert(sysUserDept2);
            } else if (!sysUserDept.getDeptId().equals(dept_id)) {
                SysUserDept sysUserDept1 = new SysUserDept();
                sysUserDept1.setUserId(user_id);
                sysUserDept1.setDeptId(dept_id);
                sysUserDeptMapper.deleteByUserId(user_id);
                sysUserDeptMapper.insert(sysUserDept1);
            } else {
                System.out.println("该用户已绑定公司");
            }

            SysUser sysUser = sysUserMapper.selectByPrimaryKey(user_id);
            sysUser.setDealer_id(examDetailVo.getDealer_id());
            sysUser.setRealName(examDetailVo.getName());
            sysUserMapper.updateByPrimaryKey(sysUser);
        }

        SysCustomer sysCustomer = sysCustomerMapper.selectByPrimaryKey(customer_id);

        if (sysCustomer == null) {
            return ServerResponse.createByErrorMessage("客户不存在");
        }
        sysCustomer.setDealerId(examDetailVo.getDealer_id());
        sysCustomer.setSalesmanId(examDetailVo.getSalesman_id());

//        if (sysCustomer.getDealerId()!=examDetailVo.getDealer_id()){
//            Integer count = mallOrderMapper.checkOrderNum(customer_id,sysCustomer.getDealerId());
//            mallOrderMapper.changeDealer(customer_id,sysCustomer.getDealerId(),examDetailVo.getDealer_id());
//        }
        sysCustomerMapper.updateByPrimaryKey(sysCustomer);

        //判断该客户是否创建了计划
        //获得该客户最早注册的用户
        Integer user_id2 = sysCustomerMapper.selectCustomerUserId(customer_id);
        if (user_id2 == null) {
            return ServerResponse.createByErrorMessage("该客户下没有用户");
        }
        Date date = new Date();
        List list = mallProductPlanMapper.checkPlan(user_id2, date);
        if (list.size() == 0) {
            //创建今年十二个月的生成计划
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            for (int i = 1; i <= 12; i++) {
                calendar.set(Calendar.MONTH, i - 1);
                planManageService.createPlan(customer_id, calendar.getTime());
            }
        }

        return ServerResponse.createBySuccess("审核成功");
    }

    @PostMapping("failExam")
    @ApiOperation(value = "不通过审核")
    public ServerResponse failExam(Integer temp_id, String opinion) {
        System.out.println(temp_id);
        System.out.println(opinion);
        sysUserTempMapper.failExam(temp_id, opinion);

        return null;
    }
}
